from django import newforms as forms
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
import re
GENDER_CHOICES = (
    ('M', _('Masculino')),
    ('F', _('Femenino'))
)
class RegistroForm(forms.Form):
    usuario = forms.CharField(max_length=30)
    password1 = forms.CharField(widget=forms.PasswordInput())
    password2 = forms.CharField(widget=forms.PasswordInput())
    nombre = forms.CharField(max_length=60)
    apellidos = forms.CharField(max_length=60)
    correo = forms.EmailField()
    sexo = forms.ChoiceField(choices=GENDER_CHOICES)

    def isValidUsername(self, user):
        try:
            User.objects.get(username=user)
        except User.DoesNotExist:
            return
        error = forms.ValidationError(_('A user with that username already exists.'))
        self.errors['usuario'] = error.messages
        raise error

    def clean_password(self):
        p1 = self.clean_data['password1']
        p2 = self.clean_data['password2']
        if p1 != p2:
            error = forms.ValidationError(_("Las contrasenias no concuerdan"))
            self.errors['password2'] = error.messages
            raise error
        return p1

    def save(self, new_data):
        "Creates the user."
        return User.objects.create_user(**new_data)


class ProblemaForm(forms.Form):
    dicts = {'cols':60, 'rows':10}
    lenguajes = forms.ChoiceField()
    codigo = forms.CharField(widget=forms.Textarea(attrs=dicts))
    salida = forms.CharField(widget=forms.Textarea(attrs=dicts))
    entrada = forms.CharField(widget=forms.Textarea(attrs=dicts))


class RegistrationForm(forms.Form):
    username = forms.CharField(label='Username', max_length=30)
    email = forms.EmailField(label='Email')
    password1 = forms.CharField(label='Password', widget= forms.PasswordInput())
    password2 = forms.CharField(label='Password(again)', widget = forms.PasswordInput())

    def clean_password2(self):
        if 'password1' in self.data:
            password1 = self.clean_data['password1']
            password2 = self.clean_data['password2']
            if password1 == password2:
                return password2
            raise forms.ValidationError("Las contrasenias no coinciden")
    def clean_username(self):
        username = self.clean_data['username']
        if not re.search(r'^\w+$',username):
            raise forms.ValidationError("El usuario solo puede contener caracteres alfanumericos a-z 0-9 A-Z _")
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError("El nombre de usuario ya esta siendo usado")

class PasswordChangeForm(forms.Form):
    password1 = forms.CharField(label='Password Actual', widget=forms.PasswordInput())
    newpassword1 = forms.CharField(label='Nuevo Password', widget=forms.PasswordInput())
    newpassword2 = forms.CharField(label='Nuevo Password', widget=forms.PasswordInput())
    def __init__(self, request=None, *args, **kwargs):
        super(PasswordChangeForm, self).__init__(*args, **kwargs)
        self.request = request
    def clean_password1(self):
        if self.request:
            if self.request.user.check_password(self.clean_data['password1']):
                return self.clean_data['password1']
            raise forms.ValidationError("El password actual no coincide")
        raise forms.ValidationError("El password actual no coincide")
    def clean_newpassword2(self):
        if 'password1' in self.data:
            newpassword1 = self.clean_data['newpassword1']
            newpassword2 = self.clean_data['newpassword2']
            if newpassword1 == newpassword2:
                return newpassword2
            raise forms.ValidationError("Las contrasenias no coinciden")